﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;

namespace Framework.Kit
{
    public enum ConfigFileType
    {
        Default=0,
        WebConfig,
        AppConfig
    }

    public class xml
    {
        /// <summary>
        /// Summary description for ReadWriteConfig.
        /// </summary>
        public class ReadWriteConfig
        {
            private string docName ;

            /// <summary>
            /// XML配置文件名
            /// </summary>
            public string DocName
            {
                get { 
                    return docName; 
                }
                set {
                    string file=AppDomain.CurrentDomain.BaseDirectory + value;
                    if (System.IO.File.Exists(file))
                    {
                        docName = file;
                    }
                    else
                    {
                        XmlDocument xmldoc = new XmlDocument();
                        xmldoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<configuration>" +
                        "<appSettings>" +
                        "</appSettings>" +
                        "</configuration>" );
                        xmldoc.Save(file);
                    }
                    docName = file;
                }
            }

            private XmlNode node = null;
            private int _configType;
            public string message;

            public int ConfigType
            {
                get { return _configType; }
                set { _configType = value; }
            }

            /// <summary>
            /// 根据key,获取键值
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public string GetValue(string key)
            {
                try
                {
                    XmlDocument cfgDoc = new XmlDocument();
                    loadConfigDoc(cfgDoc); 
                    node = cfgDoc.SelectSingleNode("//appSettings");
                    if (node == null)
                    {
                        throw new InvalidOperationException("appSettings section not found");
                    }    
                    XmlElement sltElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
                    if (sltElem == null)
                    {
                        return null;
                    }
                    message = System.Configuration.ConfigurationManager.AppSettings[key];
                    return message;
                }
                catch(Exception ex)
                {
                    other.WriteErrLog("操作异常，获取value值失败！", ex);
                    return null;
                }
            }


            public string SetValue(string key, string value)
            {
                XmlDocument cfgDoc = new XmlDocument();
                loadConfigDoc(cfgDoc);
                node = cfgDoc.SelectSingleNode("//appSettings");
                if (node == null)
                {
                    throw new InvalidOperationException("appSettings section not found");
                }
                try
                { 
                    XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
                    if (addElem != null)
                    {
                        message = "此key已经存在！";
                        return message;
                    }
                    else
                    {
                        XmlElement entry = cfgDoc.CreateElement("add");
                        entry.SetAttribute("key", key);
                        entry.SetAttribute("value", value);
                        node.AppendChild(entry);
                    }
                    saveConfigDoc(cfgDoc, DocName);
                    message = "添加成功！";
                    return message;
                }
                catch(Exception ex)
                {
                    message = "操作异常，添加失败！";
                    other.WriteErrLog(message, ex);
                    return message;
                }
            }


            private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
            {
                try
                {
                    XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
                    writer.Formatting = Formatting.Indented;
                    cfgDoc.WriteTo(writer);
                    writer.Flush();
                    writer.Close();
                    return;
                }
                catch
                {
                    throw;
                }
            }


            public string removeElement(string elementKey)
            {
                try
                {
                    XmlDocument cfgDoc = new XmlDocument();
                    loadConfigDoc(cfgDoc);  
                    node = cfgDoc.SelectSingleNode("//appSettings");
                    if (node == null)
                    {
                        throw new InvalidOperationException("appSettings section not found");
                    }

                    XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + elementKey + "']");
                    if (addElem == null)
                    {
                        message = "此key不存在！";
                        return message;
                    }   
                    node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
                    saveConfigDoc(cfgDoc, DocName);
                    message = "删除成功！";
                    return message;
                }
                catch(Exception ex)
                {
                    message = "操作异常，删除失败！";
                    other.WriteErrLog(message, ex);
                    return message;
                }
            }

            public string modifyElement(string elementKey, string elementValue)
            {
                try
                {
                    XmlDocument cfgDoc = new XmlDocument();
                    loadConfigDoc(cfgDoc);
                    node = cfgDoc.SelectSingleNode("//appSettings");
                    if (node == null)
                    {
                        throw new InvalidOperationException("appSettings section not found");
                    }   
                    XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + elementKey + "']");
                    if (addElem == null)
                    {
                        message = "此key不存在！";
                        return message;
                    }

                    addElem.SetAttribute("value", elementValue);
                    saveConfigDoc(cfgDoc, DocName);
                    message = "修改成功！";
                    return message;
                }
                catch( Exception ex)
                {
                    message = "操作异常，修改失败！";
                    other.WriteErrLog(message, ex);
                    return message;
                }
            }


            private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
            { 
                if (Convert.ToInt32(ConfigType) == Convert.ToInt32(ConfigFileType.AppConfig))
                {
                    DocName = ((Assembly.GetEntryAssembly()).GetName()).Name;
                    DocName += ".exe.config";
                }
                else
                {
                    //docName=HttpContext.Current.Server.MapPath("web.config");
                }
                cfgDoc.Load(DocName);
                return cfgDoc;
            }
        }
    }
}
